package com.hbnu.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.mapper.PatentMapper;
import com.hbnu.system.mapper.PatentqualificationMapper;
import com.hbnu.system.model.QualificationDTO.PatentQualificationDTO;
import com.hbnu.system.model.context.BaseContext;
import com.hbnu.system.model.dto.PatentDTO;
import com.hbnu.system.model.entity.*;
import com.hbnu.system.service.*;
import com.hbnu.system.utils.CheckRoleUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;

@Service
public class PatentQualificationServiceImpl extends ServiceImpl<PatentqualificationMapper, Patent_Qualification> implements IPatentQualificationSerivce {

    @Autowired
    private IPatentService iPatentService;

    @Autowired
    private IPatentTypeService iPatentTypeService;

    @Autowired
    private PatentMapper patentMapper;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private CheckRoleUtil checkRoleUtil;

    @Autowired
    private IPatentauthorService iPatentauthorService;

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");


    @Override
    public boolean addPatent_Qualification(PatentQualificationDTO patentQualificationDTO) {

        // 1. 权限校验：普通用户仅能操作【草稿】状态专利
        Patent patent = iPatentService.getPatentById(patentQualificationDTO.getPatentID());
        checkRoleUtil.checkPermissionAchievement(patent.getStatus());

        // 2. 专利存在性校验
        PatentDTO patentDTO = iPatentService.getPatentDTOById(patentQualificationDTO.getPatentID());
        if (Objects.isNull(patentDTO)) {
            throw new BaseException("专利编号有误!");
        }

        if(Objects.nonNull(this.getOne(Wrappers.lambdaQuery(Patent_Qualification.class)
                .eq(Patent_Qualification::getPatentID,patentQualificationDTO.getPatentID())))){
            throw new BaseException("已经存在量化数据!");
        }

        float finalValue;
        Patent_Qualification patentQualification = new Patent_Qualification();

        if(patentQualificationDTO.getManualScoreMode()=="true"){
            finalValue=patentQualificationDTO.getFinalValue();
            patentQualificationDTO.setFinalValue(patentQualificationDTO.getFinalValue());
            patentQualificationDTO.setNote(patentQualificationDTO.getNote());
            BeanUtils.copyProperties(patentQualificationDTO, patentQualification);
            System.out.println("patentQualificationDTO="+patentQualification);
            System.out.println("11111111"+patentQualification);
        }else {
            // 4. 类型参数完整性校验
            Integer type1ID = patentQualificationDTO.getType1ID();
            Integer type2ID = patentQualificationDTO.getType2ID();
            Integer type3ID = patentQualificationDTO.getType3ID();
            if (Objects.isNull(type1ID) || Objects.isNull(type2ID) || Objects.isNull(type3ID)) {
                throw new BaseException("请完整填写类型数据（Type1ID/Type2ID/Type3ID）!");
            }

            // 5. 查询专利类型配置（必查，用于获取类型名称）
            Patent_Type patentType = iPatentTypeService.getOne(Wrappers.lambdaQuery(Patent_Type.class)
                    .eq(Patent_Type::getType1ID, type1ID)
                    .eq(Patent_Type::getType2ID, type2ID)
                    .eq(Patent_Type::getType3ID, type3ID));
            if (Objects.isNull(patentType)) {
                throw new BaseException("未找到匹配的专利类型配置，请检查Type1ID/Type2ID/Type3ID!");
            }

            // 6. 区分国际专利场景（Type1=2，Type2=26，Type3=0）
            boolean isInternationalPatent = (type1ID == 2 && type2ID == 26 && type3ID == 0);

            if (isInternationalPatent) {
                // 国际专利：校验用户填写的分数
                if (Objects.isNull(patentQualificationDTO.getFinalValue()) || patentQualificationDTO.getFinalValue() <= 0) {
                    throw new BaseException("国际专利需填写有效分数（>0）!");
                }
                finalValue = patentQualificationDTO.getSc();
            } else {
                // 其他类型：从配置计算分数
                finalValue = patentType.getValue();
                if (type1ID == 3 || type1ID == 4) { // 许可/转让类
                    if (Objects.isNull(patentQualificationDTO.getFunds()) || patentQualificationDTO.getFunds() <= 0) {
                        throw new BaseException("技术实施许可/转让类必须填写有效到账经费（>0万元）!");
                    }
                    finalValue *= patentQualificationDTO.getFunds();
                }
                finalValue = Math.round(finalValue * 100) / 100f; // 保留两位小数
            }


            BeanUtils.copyProperties(patentQualificationDTO, patentQualification);

            // 8. 填充类型名称并入库（统一从patentType获取）
            patentQualification.setFinalValue(finalValue)
                    .setPatentType1(patentType.getPatentType1())
                    .setPatentType2(patentType.getPatentType2())
                    .setPatentType3(patentType.getPatentType3());

            System.out.println("22222222"+patentQualification);
        }

        // 7. 更新专利主表分数
        patentDTO = iPatentService.getPatentDTOById(patentQualificationDTO.getPatentID());
        patentDTO.setScore(finalValue);
        Patent patentEntity = new Patent();
        BeanUtils.copyProperties(patentDTO, patentEntity);
        iPatentService.updatePatent(patentEntity);

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        String patentid=patentQualification.getPatentID();
        System.out.println("patent="+iPatentService.getPatentById(patentid));
        List<Patentauthor> patentauthorList = iPatentauthorService.listAuthor(patent.getPatentID());
        System.out.println("patentauthorList="+patentauthorList);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (patentauthorList != null && !patentauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (patentauthorList.size() == 1) {
                Patentauthor soleAuthor = patentauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Patentauthor author : patentauthorList) {
                    iPatentauthorService.updatePatentAuthor(author);
                }
            }
        }

        return baseMapper.insert(patentQualification) > 0;

    }

    /**
     * 删除量化分数
     * @param patentQualificationID
     * @return
     */
    @Override
    public boolean deletePatent_Qualification(String patentQualificationID) {

        Patent_Qualification existEntity = baseMapper.selectById(patentQualificationID);
        if (Objects.isNull(existEntity)) {
            throw new BaseException("量化数据不存在!");
        }

        // 权限校验
        Patent patent = iPatentService.getPatentById(existEntity.getPatentID());
        checkRoleUtil.checkPermissionAchievement(patent.getStatus());

        // 清空专利主表分数
        PatentDTO patentDTO = iPatentService.getPatentDTOById(existEntity.getPatentID());
        patentDTO.setScore(0f);
        Patent patentEntity = new Patent();
        BeanUtils.copyProperties(patentDTO, patentEntity);
        iPatentService.updatePatent(patentEntity);

        List<Patentauthor> patentauthorList = iPatentauthorService.listAuthor(existEntity.getPatentID());
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (patentauthorList != null && !patentauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (patentauthorList.size() == 1) {
                Patentauthor soleAuthor = patentauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Patentauthor author : patentauthorList) {
                    iPatentauthorService.updatePatentAuthor(author);
                }
            }
        }

        return baseMapper.deleteById(patentQualificationID) > 0;
    }

    @Override
    public List<Patent_Qualification> getOnePatent_Qualification(String PatentID) {
        Patent patent = iPatentService.getPatentById(PatentID);
        if(Objects.isNull(patent)){
            throw new BaseException("专利编号有误!");
        }

        List<Patent_Qualification> patent_qualifications = baseMapper.selectList(Wrappers.lambdaQuery(Patent_Qualification.class)
                .eq(Patent_Qualification::getPatentID, PatentID));

        return patent_qualifications;
    }

    /**
     * 修改专利分值
     * @param patentQualification
     * @return
     */
    @Override
    public boolean upPatentScore(Patent_Qualification patentQualification) {

        Patent_Qualification existEntity = baseMapper.selectById(patentQualification.getPatentQualificationID());
        if (Objects.isNull(existEntity)) {
            throw new BaseException("量化数据不存在!");
        }

        // 权限校验
        Patent patent = iPatentService.getPatentById(existEntity.getPatentID());
        checkRoleUtil.checkPermissionAchievement(patent.getStatus());

        // 区分国际专利场景
        boolean isInternationalPatent = (existEntity.getType1ID() == 2
                && existEntity.getType2ID() == 26
                && existEntity.getType3ID() == 0);

        if (isInternationalPatent) {
            // 国际专利：直接使用传入的分数（校验有效性）
            if (Objects.isNull(patentQualification.getFinalValue()) || patentQualification.getFinalValue() <= 0) {
                throw new BaseException("国际专利需填写有效分数（>0）!");
            }
            existEntity.setFinalValue(patentQualification.getFinalValue());
        } else {
            // 非国际专利：禁止手动修改（若需支持，需重新走配置计算逻辑）
            throw new BaseException("仅国际专利支持自主修改分数!");
        }

        // 更新分值 & 同步专利主表
        baseMapper.updateById(existEntity);
        PatentDTO patentDTO = iPatentService.getPatentDTOById(existEntity.getPatentID());
        patentDTO.setScore(existEntity.getFinalValue());
        Patent patentEntity = new Patent();
        BeanUtils.copyProperties(patentDTO, patentEntity);
        iPatentService.updatePatent(patentEntity);

        String Pscore = "0.00";
        String patentid=patentQualification.getPatentID();
        List<Patentauthor> patentauthorList = iPatentauthorService.listAuthor(patentid);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (patentauthorList != null && !patentauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (patentauthorList.size() == 1) {
                Patentauthor soleAuthor = patentauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Patentauthor author : patentauthorList) {
                    iPatentauthorService.updatePatentAuthor(author);
                }
            }
        }
        return true;

    }




    @Override
    public Patent_Qualification getById(String id){
        Patent_Qualification patent_qualification = baseMapper.selectOne(Wrappers.lambdaQuery(Patent_Qualification.class)
                .eq(Patent_Qualification::getPatentID, id));
        return patent_qualification;
    }

}
